package com.waves.core.config;

import com.waves.core.constant.MQConstant;
import com.waves.core.constant.TimeConstant;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.Exchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;

/**
 * 通过死信队列 实现延迟队列配置
 *
 * @author dlw
 */
@Configuration
public class MyRabbitMQDelayConfig {


    /**
     * 交换机
     *
     * @return
     */
    @Bean
    public Exchange stockDelayExchange() {
        return new TopicExchange(MQConstant.ORDER_DELAY_EXCHANGE, true, false);
    }


    /**
     * 普通队列
     *
     * @return
     */
    @Bean
    public Queue stockCommonQueue() {
        return new Queue(MQConstant.STOCK_COMMON_QUEUE, true, false, false);
    }

    /**
     * 死信队列
     * 队列存放消息不会被消费 超时自动投递到普通队列
     *
     * @return
     */
    @Bean
    public Queue stockDelay() {
        HashMap<String, Object> arguments = new HashMap<>();
        arguments.put("x-dead-letter-exchange", MQConstant.ORDER_DELAY_EXCHANGE);
        arguments.put("x-dead-letter-routing-key", "stock.release");
        arguments.put("x-message-ttl", 2 * TimeConstant.DAY_TIME);
//        arguments.put("x-message-ttl", 60 * 1000);
        return new Queue(MQConstant.STOCK_DELAY_QUEUE, true, false, false, arguments);
    }


    /**
     * 交换机与普通队列绑定
     *
     * @return
     */
    @Bean
    public Binding stockCommonBinding() {
        return new Binding(MQConstant.STOCK_COMMON_QUEUE,
                Binding.DestinationType.QUEUE,
                MQConstant.ORDER_DELAY_EXCHANGE,
                "stock.release.#",
                null);
    }

    /**
     * 交换机与死信队列绑定
     *
     * @return
     */
    @Bean
    public Binding stockLockedBinding() {
        return new Binding(MQConstant.STOCK_DELAY_QUEUE,
                Binding.DestinationType.QUEUE,
                MQConstant.ORDER_DELAY_EXCHANGE,
                "stock.locked",
                null);
    }


}
